package proxynew;

import java.util.Iterator;
import java.util.LinkedList;

public class MessageCache {
	
	private static MessageCache instance = null;
	LinkedList<CachedMessage> messages;
	
	private MessageCache() {
		messages = new LinkedList<CachedMessage>();
	}

	public static MessageCache getInstance() {
		if (instance == null) {
			instance = new MessageCache();
		}
		return instance;
	}
	
	public boolean isInCache(String grupo, byte[] data) {
		synchronized (messages) {
			int key = generateHash(grupo, data);
			Iterator<CachedMessage> itMessages = messages.iterator();
			while (itMessages.hasNext()) {
				CachedMessage msg = itMessages.next();
				// mensagens em cache que foram adicionados nos ultimos 5 seg
				if ((msg.hash == key) && ((System.currentTimeMillis() - msg.added) < (10 * 1000))) {
					return true;
				}
			}
		}
		return false;
	}

	public void addMessageToCache(String grupo, byte[] data) {
		if (!isInCache(grupo, data)) {
			synchronized (messages) { 
				CachedMessage msg = new CachedMessage();
				msg.hash = generateHash(grupo, data);
				msg.added = System.currentTimeMillis();
				
				messages.addFirst(msg);
				if (messages.size() > 20) {
					messages.removeLast();
				}
			}
		}
	}
	
	private int generateHash(String grupo, byte[] data) {
		return (grupo + new String(data)).hashCode();
	}
	
	class CachedMessage {
		int hash;
		long added;
	}
}
